package top.rish.rib.ware.sys.service;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import top.rish.rib.base.utils.StpUserUtil;
import top.rish.rib.base.ware.BaseServiceImpl;
import top.rish.rib.ware.sys.dto.UserLoginDto;
import top.rish.rib.ware.sys.entity.User;
import top.rish.rib.ware.sys.mapper.UserMapper;
import top.rish.rib.ware.sys.vo.UserLoginVo;

@Component
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {

    @Override
    public UserLoginVo login(Context ctx) {
        if(StpUserUtil.adminStp.isLogin()) {
            User userInDb = this.getById(StpUserUtil.adminStp.getLoginIdAsString());
            UserLoginVo res = new UserLoginVo();
            res.setId(userInDb.getId());
            res.setUsername(userInDb.getUsername());
            res.setRealName(userInDb.getRealName());
            res.setTokenInfo(StpUserUtil.adminStp.getTokenInfo());
            return res;
        }
        UserLoginDto dto = this.validJson(ctx, UserLoginDto.class);
        User queryUser = new User();
        queryUser.setUsername(dto.getUsername());
        long c = this.baseMapper.templateCount(queryUser);
        if (c != 1) {
            throw  new RuntimeException("账号或密码错误");
        }
        User userInDb = this.baseMapper.templateOne(queryUser);
        if(ObjectUtil.isEmpty(userInDb.getPassword())){
            throw new RuntimeException("账号或密码错误");
        }
        String md5pwd =
                 SecureUtil.hmacMd5(dto.getPassword())
                .digestHex(userInDb.getUsername());
        if (ObjectUtil.notEqual(userInDb.getPassword(), md5pwd )) {
            throw  new RuntimeException("账号或密码错误");
        }
        StpUserUtil.adminStp.login(userInDb.getId());
        UserLoginVo res = new UserLoginVo();
        res.setId(userInDb.getId());
        res.setUsername(userInDb.getUsername());
        res.setRealName(userInDb.getRealName());
        res.setTokenInfo(StpUserUtil.adminStp.getTokenInfo());
        return res;
    }

    @Override
    public boolean logout(Context ctx) {
        if(!StpUserUtil.adminStp.isLogin()) {
            return false;
        }
        StpUserUtil.adminStp.logout();
        return true;
    }
}
